import React, {useState} from "react";
import {Button, Grid} from "@material-ui/core";
import AddRounded from "@material-ui/icons/AddRounded";

import {EnhancedTable, Toolbar} from "../../shared/components";
import {getTeamMembers} from "../../shared/services/data.service";
import {getFullName} from "../../shared/utilities/common.util";

const ViewAllMember = ({onAdd, onRowClick, ...props}) => {
    const [teamMembers, setTeamMembers] = useState([]);

    const getMemberList = () => (
        new Promise((resolve, reject) => {
            getTeamMembers().then(res => {
                setTeamMembers(res.data);
                resolve(res.data);
            }).catch(error => reject(error));
        })
    );

    const renderUser = row => getFullName(row.first_name, row.last_name);

    return (
        <Grid container spacing={4}>
            <Toolbar
                title="Team Management"
                actions={<React.Fragment>
                    <Button
                        variant="contained"
                        color="primary"
                        startIcon={<AddRounded/>}
                        onClick={onAdd}
                    >
                        Add Member
                    </Button>
                </React.Fragment>}
            />

            <Grid item xs={12}>
                <EnhancedTable
                    title={"Team List"}
                    schema={[
                        {id: 'id', label: 'Id', hidden: true},
                        {id: 'name', label: 'User', sort: true, type: 'render', render: renderUser},
                        {id: 'userId', label: 'User Id', sort: true},
                        {id: 'email', label: 'Email', sort: true},
                        {id: 'role', label: 'Role', sort: true}
                    ]}
                    async={{loading: true, loadingData: getMemberList}}
                    pagination={teamMembers.length > 5}
                    onRowClick={onRowClick}
                />
            </Grid>
        </Grid>
    );
};

export default ViewAllMember;
